/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.monitor;

import cn.star.framework.core.dict.EnumEntry;
import cn.star.framework.monitor.annotation.MonitorMethod.Null;
import cn.star.framework.monitor.core.IMonitorInvoke;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
 * <br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
@EnableAsync
public class MonitorInvokeProxy {
  @Autowired private ApplicationContext applicationContext;

  public void invoke(MonitorContext context, InvokeType type) {
    try {
      IMonitorInvoke invoke = context.getMonitorInvoke(applicationContext, type);
      if (!(invoke instanceof Null)) {
        invoke.invoke(context);
      }
    } catch (Exception e) {
      log.warn("Exception occurred during method call, {}", e.getMessage());
    }
  }

  @Async
  public void invokeAsync(MonitorContext context, InvokeType type) {
    this.invoke(context, type);
  }

  /**
   * {@link IMonitorInvoke#invoke(MonitorContext)}执行时机<br>
   *
   * @author zhaoweiping
   *     <p style='color: red'>Created on 2024-09-23 11:06:00
   * @since 3.0.0
   */
  public enum InvokeType implements EnumEntry<String> {
    /** */
    BEFORE("主方法执行前执行"),
    /** */
    BEFORE_ASYNC("主方法执行前执行(异步)"),
    /** */
    AFTER("主方法执行后执行"),
    /** */
    AFTER_ASYNC("主方法执行后执行(异步)");

    @Getter private final String label;

    InvokeType(String label) {
      this.label = label;
    }
  }
}
